import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { User } from './entities/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async findOne(username: string): Promise<User | null> {
    return this.usersRepository.findOne({
      where: { username }
    });
  }

  async findById(id: number): Promise<User | null> {
    return this.usersRepository.findOne({ where: { id } });
  }

  async findEmployees(user: User): Promise<User[]> {
    const { id, role } = user

    if (role === 0) {
      const allEmployee: User[] = await this.usersRepository.find({
        where: {
          role: Not(0),
        },
      })
      return allEmployee || [];
    }

    const findUser = await this.usersRepository.findOne({
      where: {
        id,
      },
      relations: ['subordinates'],
    });
    return findUser?.subordinates || [];
  }

  async create(user: Partial<User>): Promise<User> {
    const newUser = this.usersRepository.create(user);
    return this.usersRepository.save(newUser);
  }
} 